/**
 * 
 */
package com.taobao.snowsnow.taobao;

import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.tree.DefaultElement;

import com.taobao.api.ApiException;
import com.taobao.api.request.LogisticsOfflineSendRequest;
import com.taobao.api.request.LogisticsOnlineSendRequest;
import com.taobao.api.request.LogisticsTraceSearchRequest;
import com.taobao.api.response.LogisticsOfflineSendResponse;
import com.taobao.api.response.LogisticsOnlineSendResponse;
import com.taobao.api.response.LogisticsTraceSearchResponse;

/**
 * @author qinanhg@gmail.com
 * 创建时间: 2012-9-19 上午9:39:46
 */
public class Logistics extends Taobao {
	
	/**
	 * 线下发货(自己联系物流)
	 * @param tid
	 * 			淘宝订单号
	 * @param outSid
	 * 			快递单号
	 * @param companyCode
	 * 			快递公司代码
	 * @return
	 * 			发货失败的信息, 成功返回的信息为Null
	 * @throws ApiException
	 * 			调用淘宝API出错
	 * @throws DocumentException
	 * 			解析XML出错
	 */
	public static String offlineSendGoods(long tid, String outSid, String companyCode) throws ApiException, DocumentException {
		LogisticsOfflineSendRequest req=new LogisticsOfflineSendRequest();
		req.setTid(tid);
		req.setOutSid(outSid);
		req.setCompanyCode(companyCode);
		LogisticsOfflineSendResponse response = client.execute(req , TaoBaoUtil.SESSIONKEY);
		
		Document doc = DocumentHelper.parseText(response.getBody());
		@SuppressWarnings("unchecked")
		List<DefaultElement> l = doc.selectNodes("//error_response");
		
		String sub_msg = null;
		for (DefaultElement d : l) {
			sub_msg = d.element("sub_msg").getText();
		}
		
		return sub_msg;
	}
	
	public static String onlineSendGoods(long tid, String outSid, String companyCode) throws ApiException, DocumentException {
		LogisticsOnlineSendRequest req=new LogisticsOnlineSendRequest();
		req.setTid(tid);
		req.setOutSid(outSid);
		req.setCompanyCode(companyCode);
		LogisticsOnlineSendResponse response = client.execute(req , TaoBaoUtil.SESSIONKEY);
		
		Document doc = DocumentHelper.parseText(response.getBody());
		@SuppressWarnings("unchecked")
		List<DefaultElement> l = doc.selectNodes("//error_response");
		
		String sub_msg = null;
		for (DefaultElement d : l) {
			sub_msg = d.element("sub_msg").getText();
		}
		
		return sub_msg;
	}
	
	public static String traceSearch(long tid) throws ApiException {
		LogisticsTraceSearchRequest req=new LogisticsTraceSearchRequest();
		req.setTid(tid);
		req.setSellerNick("myleft1");
		LogisticsTraceSearchResponse rep = client.execute(req);
		
		return rep.getBody();
	}
	
	public static void main(String[] args) {
		try {
			System.out.println(Logistics.offlineSendGoods(234l, "234", "sto"));
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
